package com.zf.bm.common.utils;

import com.zf.bm.common.constant.HttpHeaderConstant;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;


import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Optional;
import java.util.regex.Pattern;

/**
 * 字符串工具类, 继承org.apache.commons.lang3.StringUtils类
 */
@Slf4j
public class StringUtil extends org.apache.commons.lang3.StringUtils {
	
    private static final char SEPARATOR = '_';
    private static final String CHARSET_NAME = "UTF-8";
    
    /**
     * 转换为字节数组
     * @param str
     * @return
     */
    public static byte[] getBytes(String str){
    	if (str != null){
    		try {
				return str.getBytes(CHARSET_NAME);
			} catch (UnsupportedEncodingException e) {
				return null;
			}
    	}else{
    		return null;
    	}
    }
    
    /**
     * 转换为字节数组
     * @return
     */
    public static String toString(byte[] bytes){
    	try {
			return new String(bytes, CHARSET_NAME);
		} catch (UnsupportedEncodingException e) {
			return EMPTY;
		}
    }
    

	/**
	 * 转换为Double类型
	 */
	public static Double toDouble(Object val){
		if (val == null){
			return 0D;
		}
		try {
			return Double.valueOf(trim(val.toString()));
		} catch (Exception e) {
			return 0D;
		}
	}

	/**
	 * 转换为Float类型
	 */
	public static Float toFloat(Object val){
		return toDouble(val).floatValue();
	}

	/**
	 * 转换为Long类型
	 */
	public static Long toLong(Object val){
		return toDouble(val).longValue();
	}

	/**
	 * 转换为Integer类型
	 */
	public static Integer toInteger(Object val){
		return toLong(val).intValue();
	}

	/**
	 * 驼峰命名法工具
	 * @return
	 * 		toCamelCase("hello_world") == "helloWorld" 
	 * 		toCapitalizeCamelCase("hello_world") == "HelloWorld"
	 * 		toUnderScoreCase("helloWorld") = "hello_world"
	 */
    public static String toCamelCase(String s) {
        if (s == null) {
            return null;
        }


        StringBuilder sb = new StringBuilder(s.length());
        boolean upperCase = false;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);

            if (c == SEPARATOR) {
                upperCase = true;
            } else if (upperCase) {
                sb.append(Character.toUpperCase(c));
                upperCase = false;
            } else {
                sb.append(c);
            }
        }

        return sb.toString();
    }

    /**
	 * 驼峰命名法工具
	 * @return
	 * 		toCamelCase("hello_world") == "helloWorld" 
	 * 		toCapitalizeCamelCase("hello_world") == "HelloWorld"
	 * 		toUnderScoreCase("helloWorld") = "hello_world"
	 */
    public static String toCapitalizeCamelCase(String s) {
        if (s == null) {
            return null;
        }
        s = toCamelCase(s);
        return s.substring(0, 1).toUpperCase() + s.substring(1);
    }
    
    /**
	 * 驼峰命名法工具
	 * @return
	 * 		toCamelCase("hello_world") == "helloWorld" 
	 * 		toCapitalizeCamelCase("hello_world") == "HelloWorld"
	 * 		toUnderScoreCase("helloWorld") = "hello_world"
	 */
    public static String toUnderScoreCase(String s) {
        if (s == null) {
            return null;
        }

        StringBuilder sb = new StringBuilder();
        boolean upperCase = false;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);

            boolean nextUpperCase = true;

            if (i < (s.length() - 1)) {
                nextUpperCase = Character.isUpperCase(s.charAt(i + 1));
            }

            if ((i > 0) && Character.isUpperCase(c)) {
                if (!upperCase || !nextUpperCase) {
                    sb.append(SEPARATOR);
                }
                upperCase = true;
            } else {
                upperCase = false;
            }

            sb.append(Character.toLowerCase(c));
        }

        return sb.toString();
    }
 
    /**
     * 转换为JS获取对象值，生成三目运算返回结果
     * @param objectString 对象串
     *   例如：row.user.id
     *   返回：!row?'':!row.user?'':!row.user.id?'':row.user.id
     */
    public static String jsGetVal(String objectString){
    	StringBuilder result = new StringBuilder();
    	StringBuilder val = new StringBuilder();
    	String[] vals = split(objectString, ".");
    	for (int i=0; i<vals.length; i++){
    		val.append("." + vals[i]);
    		result.append("!"+(val.substring(1))+"?'':");
    	}
    	result.append(val.substring(1));
    	return result.toString();
    }

	/**
	 * 获得用户远程地址
	 */
	public static String getRemoteAddr(HttpServletRequest request) {
		String remoteAddr = StringUtil.getStringValue(request.getHeader(HttpHeaderConstant.X_REAL_IP)
				, request.getHeader(HttpHeaderConstant.X_FORWARDER_FOR)
				, request.getHeader(HttpHeaderConstant.PROXY_CLIENT_IP)
				, request.getHeader(HttpHeaderConstant.WL_PROXY_CLIENT_IP));

		if (remoteAddr != null) {
			return remoteAddr;
		}
		return "0:0:0:0:0:0:0:1".equals(request.getRemoteAddr()) ? "127.0.0.1" : request.getRemoteAddr();
	}


	/**
	 * 正则匹配
	 * @param patternString 正则表达式
	 * @param str  匹配字符串
	 * @return
	 */
	public static boolean match(String patternString,String str){
		if(patternString!=null && str!=null){
			Pattern pattern = Pattern.compile(patternString);
			return pattern.matcher(str).matches();
		}
		return false;
	}

	/**
	 * 驼峰格式转为下划线
	 * "helloWorld" --> "hello_world"
	 *
	 * @param param
	 * @return
	 */
	public static String cameToUnderling(String param) {
		if (param == null || "".equals(param)) {
			return "";
		}
		int len = param.length();
		StringBuilder builder = new StringBuilder();
		for (int i = 0; i < len; i++) {
			char c = param.charAt(i);
			if (Character.isUpperCase(c)) {
				builder.append("_").append(Character.toLowerCase(c));
			} else {
				builder.append(c);
			}
		}
		return builder.toString();
	}

	public static String joinLong(String split, Long[] longs) {
		if(StringUtil.isEmpty(split)){
			throw new IllegalArgumentException("分隔符不能为空");
		}

		if(longs==null || longs.length==0){
			throw new IllegalArgumentException("参数不能为空");
		}
		StringBuilder sb = new StringBuilder();
		for (Long l:longs
			 ) {
			sb.append(l).append(split);
		}

		return sb.substring(0,sb.length()-1);
	}

	public static String combinPath(String path, String name) {
		String seperator = File.separator;
		if(path.contains("\\")){
			seperator = "\\";
		}else if(path.contains("/")){
			seperator = "/";
		}


		if(path.lastIndexOf(seperator)!= path.length()-1){
			return path+seperator+name;
		}
		return path+name;
	}

	/**
	 * 依次获取字符串值，不为空返回
	 * @param objects
	 * @return
	 */
	public static String getStringValue(String... objects) {
		return Optional.ofNullable(objects)
				.filter(os -> os.length > 0)
				.map(os -> {
					for (String obj : os) {
						if (obj != null && !obj.isEmpty()) {
							return obj;
						}
					}
					return null;
				}).orElse(null);
	}
}
